def count_words(file_name, words):
    # dict将传入函数的字典，值全部置0
    d = dict.fromkeys(words, 0)

    f = open(file_name, 'r', encoding = 'utf-8')

    for s in f.readlines():
        for name in d:
            d[name] = d[name] + s.count(name)

    f.close()
    return d

n = ['宝钗', '黛玉', '元春', '探春', '湘云', '巧姐', '凤姐', '可卿', '德华']
# 直接copy Windows目录的反斜杠"\"会导致编译出错
r = count_words('D:/数据分析/Python/0全民一起玩Python/全民一起玩PythonDemo/红楼梦.txt', n) 

print(r)
